<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="开发者" prop="username" label-width="14%">
      <template>
        <el-select v-model="dataForm.userId" placeholder="请选择">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.username"
            :value="item.userId">
          </el-option>
        </el-select>
      </template>
    </el-form-item>
      <el-form-item v-model="dataForm.collegeId" label="所属学院" size="mini">
        <el-tree
          v-model="dataForm.collegeId"
          :data="collegeList"
          :props="collegeListTreeProps"
          node-key="collegeId"
          ref="collegeListTree"
          :default-expand-all="true"
          @check-change="handleCheckChange"
          show-checkbox>
        </el-tree>
      </el-form-item>
      <el-form-item label="所属实验室(未加入实验室无需勾选)" size="mini" label-width="23%">
        <template>
          <el-select v-model="dataForm.laboratoryId" placeholder="请选择">
            <el-option
              v-for="item in labList"
              :key="item.laboratoryId"
              :label="item.name"
              :value="item.laboratoryId">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
    <el-form-item label="所在团队" prop="teamId" label-width="14%">
      <template>
        <el-select v-model="dataForm.teamId" placeholder="请选择">
          <el-option
            v-for="item in teamList"
            :key="item.teamId"
            :label="item.teamName"
            :value="item.teamId">
          </el-option>
        </el-select>
      </template>
    </el-form-item>
    <el-form-item label="团队角色" prop="teamLeader" label-width="14%">
      <template>
        <el-radio v-model="dataForm.teamLeader" label="1">队长</el-radio>
        <el-radio v-model="dataForm.teamLeader" label="0">成员</el-radio>
      </template>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  export default {
    data () {
      return {
        visible: false,
        userList: [],
        teamList: [],
        collegeList: [],
        labList: '',
        username: '',
        dataForm: {
          userId: '',
          developerName: '',
          developerId: '',
          collegeId: '',
          teamLeader: '',
          laboratoryId: -1,
          teamId: ''
        },
        collegeListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataRule: {
          user_id: [
            { required: true, message: '开发者姓名不能为空', trigger: 'blur' }
          ],
          collegeId: [
            { required: true, message: '所属学院ID不能为空', trigger: 'blur' }
          ],
          teamLeader: [
            { required: true, message: '是否为团队队长（0：不是 1：是） 不能为空', trigger: 'blur' }
          ],
          laboratoryId: [
            { required: true, message: '所属实验室ID（-1：未加入实验室）不能为空', trigger: 'blur' }
          ],
          teamId: [
            { required: true, message: '所在团队编码（多个团队间用逗号间隔）不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/user/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.userList = data && data.code === 0 ? data.userList : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/college/list'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            this.collegeList = treeDataTranslate(data, 'collegeId')
          }).then(() => {
            this.visible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].resetFields()
              this.$refs.collegeListTree.setCheckedKeys([])
            })
          })
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/laboratory/select'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            this.labList = data && data.code === 0 ? data.laboratoryList : []
          }).then(() => {
            this.visible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].resetFields()
              this.$refs.collegeListTree.setCheckedKeys([])
            })
          })
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/business/team/select'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            this.teamList = data && data.code === 0 ? data.teamList : []
          }).then(() => {
            this.visible = true
            this.$nextTick(() => {
              this.$refs['dataForm'].resetFields()
              this.$refs.collegeListTree.setCheckedKeys([])
            })
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/business/developer/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.roleIdList = data.user.roleIdList
                this.dataForm.status = data.user.status
              }
            })
          }
        })
      },
      handleCheckChange(data, checked, indeterminate) {
        this.dataForm.collegeId = data.collegeId
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/business/developer/${!this.dataForm.developerId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'developerId': this.dataForm.developerId || undefined,
                'userId': this.dataForm.userId,
                'collegeId': this.dataForm.collegeId,
                'teamLeader': this.dataForm.teamLeader,
                'laboratoryId': this.dataForm.laboratoryId,
                'teamId': this.dataForm.teamId
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
